/**
 * Copyright 2008 Adam Ruggles.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.sapien.test.util;

import javax.sql.DataSource;

import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.code.sapien.guice.ConfigModule;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
/**
 * Junit4 Unit Runner for Running JUnit Tests with in a Guice environment.
 * @author Adam
 * @version $Id: GuiceUnitRunner.java 16 2009-04-12 05:05:02Z a.ruggles $
 * 
 * Created on Sep 30, 2008 at 12:10:14 PM 
 */
public class GuiceUnitRunner extends BlockJUnit4ClassRunner {
	/**
	 * The Guice Injector.
	 */
	protected Injector injector;
    /**
     * The <code>Logger</code> is used by the application to generate a log messages.
     */
    private static final Logger LOG = LoggerFactory.getLogger(GuiceUnitRunner.class);

	/**
	 * Constructor.
	 * @param klass The Unit Class.
	 * @throws InitializationError If an initialization error occurs.
	 */
	public GuiceUnitRunner(final Class<?> klass) throws InitializationError {
		super(klass);
	}

	/**
	 * {@inheritDoc}
	 * @see org.junit.internal.runners.JUnit4ClassRunner#createTest()
	 */
	@Override
    protected Object createTest()  {
		final Class<?> klass = getTestClass().getJavaClass();
		if (injector != null) {
			return injector.getInstance(klass);
		}
		final Module configModule = new ConfigModule();
		final Module dataSourceModule = new AbstractModule() {
			protected void configure() {
				bind(DataSource.class).to(DriverManagerDataSource.class);
			}
		};
		if (Module.class.isAssignableFrom(klass)) {
			try {
				injector = Guice.createInjector(
						configModule,
						dataSourceModule,
						(Module) klass.newInstance());
			} catch (InstantiationException instantiationEx) {
				LOG.error("Error occurred creating injector", instantiationEx);
			} catch (IllegalAccessException illegalAccessEx) {
				LOG.error("Error occurred creating injector", illegalAccessEx);
			}
		} else {
			injector = Guice.createInjector(
					configModule,
					dataSourceModule);
			injector.injectMembers(klass);
		}
		return injector.getInstance(klass);
	}

}
